package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.SiteModelAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.other.listener.DateAndTimeBiz;
import com.infore.airsupervise.other.listener.DateAndTimeBizImpl;
import com.infore.airsupervise.other.listener.DateAndTimeListener;
import com.infore.airsupervise.other.listener.LayoutControl;
import com.infore.airsupervise.other.listener.LayoutControlListener;
import com.infore.airsupervise.ui.fragment.PsonSelectorFragment;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.rey.material.widget.RadioButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建调查询问笔录
 */
public class SiteAskCreateActivity extends BaseTitleBarActivity {

    @BindView(R.id.tv_info_arrow)
    AwesomeTextView tvInfoArrow;
    @BindView(R.id.et_startTime)
    EditText etStartTime;
    @BindView(R.id.et_endTime)
    EditText etEndTime;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_reason)
    EditText etReason;
    @BindView(R.id.et_answerName)
    EditText etAnswerName;
    @BindView(R.id.et_answerAge)
    EditText etAnswerAge;
    @BindView(R.id.et_identify)
    EditText etIdentify;
    @BindView(R.id.et_company)
    EditText etCompany;
    @BindView(R.id.et_position)
    EditText etPosition;
    @BindView(R.id.et_relationship)
    EditText etRelationship;
    @BindView(R.id.et_address_inspect)
    EditText etAddressInspect;
    @BindView(R.id.et_postCode)
    EditText etPostCode;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_other)
    EditText etOther;
    @BindView(R.id.rb_evite_false)
    RadioButton rbEviteFalse;
    @BindView(R.id.rb_evite_true)
    RadioButton rbEviteTrue;
    @BindView(R.id.ll_info)
    TableLayout llInfo;
    @BindView(R.id.tv_note_arrow)
    AwesomeTextView tvNoteArrow;
    @BindView(R.id.rv_askModel)
    RecyclerView rvAskModel;
    @BindView(R.id.ll_ask)
    LinearLayout llAsk;

    private LayoutControlListener layoutControl;
    private LawingSiteE.NotesAsk notesAskE;

    private PsonSelectorFragment inspectFra ;// 检查人
    private PsonSelectorFragment noteFra; //记录人
    private DateAndTimeBiz dateAndTimeBiz; //时间选择的实现类

    private int position;
    private PolluterE polluterE;// 污染源

    private SiteModelAdapter adapter ; //问答列表适配器
    private List<LawingSiteE.NoteModel> noteModelList = new ArrayList<>(); //问答

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_site_ask_create);
        ButterKnife.bind(this);
        layoutControl = new LayoutControl(ctx);
        Intent it = getIntent();
        if (null != it ){
            position = it.getIntExtra(Constants.INTENT_INT_KEY,-1);
            notesAskE = (LawingSiteE.NotesAsk) it.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            polluterE = (PolluterE) it.getSerializableExtra("intent_polluter");
        }
        title.setText("创建调查询问笔录");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_CHECK);
        initView();
        if(null != notesAskE){
            setAskData();
        }else {
            notesAskE = new LawingSiteE.NotesAsk();
            //添加当前用户为默认的检查人 记录人
            inspectFra.addDefaultPson();
            noteFra.addDefaultPson();
        }
        setPolluterData();
        dateAndTimeBiz = new DateAndTimeBizImpl();
    }

    private void initView() {
        rbEviteFalse.setOnCheckedChangeListener(checkListener);
        rbEviteTrue.setOnCheckedChangeListener(checkListener);
        //检查人
        inspectFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_inspectPson,inspectFra,null).commit();
        noteFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_notePson,noteFra,null).commit();

        initRecclerView();
    }

    /**
     * 问答模板 列表设置
     */
    private void initRecclerView(){
        rvAskModel.setLayoutManager( new LinearLayoutManager(ctx));
        adapter = new SiteModelAdapter(R.layout.item_site_askmodel,noteModelList);
        rvAskModel.setAdapter(adapter);
    }

    /**
     * 保存表单信息
     */
    private void initAskData(){
        notesAskE.setAddress(etAddress.getText().toString());//地址
        notesAskE.setAddressInspect(etAddressInspect.getText().toString());//检查地址
        notesAskE.setAnswerAge(etAnswerAge.getText().toString());//被询问人年龄
        notesAskE.setAnswerName(etAnswerName.getText().toString());//被询问人
        notesAskE.setCompany(etCompany.getText().toString());//被询问人单位
        notesAskE.setStartTime(etStartTime.getText().toString()); //开始时间
        notesAskE.setEndTime(etEndTime.getText().toString());//结束时间
        notesAskE.setIdentify(etIdentify.getText().toString());//身份证
        notesAskE.setPosition(etPosition.getText().toString());//职务
        notesAskE.setPostCode(etPostCode.getText().toString());//邮编
        notesAskE.setOthers(etOther.getText().toString());//其他参加人员
        notesAskE.setReason(etReason.getText().toString());//案由
        notesAskE.setPhone(etPhone.getText().toString());//电话
        notesAskE.setRelationship(etRelationship.getText().toString()); //与本案关系
        notesAskE.setEvite(rbEviteTrue.isChecked() ? 0: 1); //是否申请回避b
        notesAskE.setNoteModels(noteModelList);
        notesAskE.setInspectPson(inspectFra.getAllPsonList()); //检查人员
        notesAskE.setNotePson(noteFra.getAllPsonList());
    }

    /**
     * 在编辑
     */
    private void setAskData(){
        etAddress.setText(notesAskE.getAddress());
        etStartTime.setText(notesAskE.getStartTime());
        etEndTime.setText(notesAskE.getEndTime());
        etReason.setText(notesAskE.getReason());
        etAnswerAge.setText(notesAskE.getAnswerAge());
        etAnswerName.setText(notesAskE.getAnswerName());
        etPosition.setText(notesAskE.getPosition());
        etPostCode.setText(notesAskE.getPostCode());
        etPhone.setText(notesAskE.getPostCode());
        etOther.setText(notesAskE.getOthers());
        etIdentify.setText(notesAskE.getIdentify());
        etRelationship.setText(notesAskE.getRelationship());
        if(notesAskE.getEvite() == 0){
            rbEviteTrue.setChecked(true);
        }else {
            rbEviteFalse.setChecked(true);
        }
        noteModelList.addAll(notesAskE.getNoteModels());

        inspectFra.addPsonList(notesAskE.getInspectPson());
        noteFra.addPsonList(notesAskE.getNotePson());
    }

    /**
     * 污染源信息
     */
    private void setPolluterData(){
        if(null != polluterE) {
            etCompany.setText(polluterE.getName());
            etAddressInspect.setText(polluterE.getAddress());
        }
    }

    private boolean isInfoShowed ;
    private  boolean isAskShowed ;
    @OnClick({R.id.ll_info_control, R.id.et_startTime, R.id.et_endTime,
            R.id.ll_ask_control,R.id.tv_askModel_add,R.id.tv_askModel_sentence ,
    R.id.et_company})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_info_control: //基本信息布局控制
                isInfoShowed = !isInfoShowed;
                layoutControl.layoutControl(isInfoShowed,llInfo,tvInfoArrow);
                break;
            case R.id.et_startTime:
                dateAndTimeBiz.getDateAndTimePicker(getSupportFragmentManager(), new DateAndTimeListener() {
                    @Override
                    public void getDateAndTimeString(String dateAndTime) {
                        etStartTime.setText(dateAndTime);
                    }
                });
                break;
            case R.id.et_endTime:
                dateAndTimeBiz.getDateAndTimePicker(getSupportFragmentManager(), new DateAndTimeListener() {
                    @Override
                    public void getDateAndTimeString(String dateAndTime) {
                        etEndTime.setText(dateAndTime);
                    }
                });
                break;
            case R.id.ll_ask_control: //问答布局控制
                isAskShowed = !isAskShowed;
                layoutControl.layoutControl(isAskShowed,llAsk,tvNoteArrow);
                break;
            case R.id.tv_askModel_add : //添加询问模块
                adapter.addData( new LawingSiteE.NoteModel());
                break;
            case R.id.tv_askModel_sentence : // 模板
                ToastUtil.showShort(ctx,"请手动填写问题");
                break;
            case R.id.et_company : //选择污染源
                ToastUtil.showShort(ctx, "选择一个污染源");
                JumpUtil.ForResultJumpFromTo(this, PolluterSearchActivity.class, 99, Constants.INTENT_INT_KEY, 1);
                break;
        }
    }

    /**
     * 是否申请回避单选组
     */
    private CompoundButton.OnCheckedChangeListener checkListener  = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                rbEviteTrue.setChecked( buttonView == rbEviteTrue);
                rbEviteFalse.setChecked( buttonView == rbEviteFalse);

            }
        }
    };

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        initAskData();
        Intent it = new Intent();
        it.putExtra(Constants.INTENT_OBJ_KEY,notesAskE);
        it.putExtra(Constants.INTENT_INT_KEY,position);
        it.putExtra("intent_polluter",polluterE);
        setResult(RESULT_OK,it);
        finish();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == RESULT_OK) { //返回污染源信息
            polluterE = (PolluterE) data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            setPolluterData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( null != dateAndTimeBiz){
            dateAndTimeBiz = null;
        }
    }
}
